package com.cloud.order.service.impl;

import com.cloud.order.client.ProductClient;
import com.cloud.order.dao.OrderDetailDao;
import com.cloud.order.dao.OrderMasterDao;
import com.cloud.order.dto.CartDTO;
import com.cloud.order.dto.OrderDTO;
import com.cloud.order.entity.OrderDetail;
import com.cloud.order.entity.OrderMaster;
import com.cloud.order.entity.ProductInfo;
import com.cloud.order.enums.OrderStatus;
import com.cloud.order.enums.PayStatus;
import com.cloud.order.enums.ResponseCode;
import com.cloud.order.exception.OrderException;
import com.cloud.order.service.OrderService;
import com.cloud.order.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private OrderMasterDao orderMasterDao;
    @Autowired
    private ProductClient productClient;


    @Override
    public OrderDTO createOrder(OrderDTO orderDTO) {
        String orderId = KeyUtil.genUniqueKey();
        /**
         * 1    查询商品信息（调用商品服务）
         * 2    计算总价
         * 3    扣库存（调用商品服务）
         * 4    订单入库
         */
        /** todo 查询商品信息（调用商品服务）*/
        List<ProductInfo> infos = productClient.listForOrder(orderDTO.getList().stream().map(OrderDetail::getProductId).collect(Collectors.toList()));

        /** todo 计算总价*/
        if (infos == null || infos.size() == 0 || (orderDTO.getList() != null && orderDTO.getList().size() != infos.size())) {
            throw new OrderException(ResponseCode.PRODUCT_NOT_EXIST);
        }

        BigDecimal payAll = BigDecimal.ZERO;
        Assert.notEmpty(orderDTO.getList(),"订单详情一定不能为空");
        for (OrderDetail orderDetail : orderDTO.getList()) {
            ProductInfo productInfo = infos.stream().filter(info -> info.getProductId().equals(orderDetail.getProductId())).findAny().get();
            payAll = productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())).add(payAll).setScale(2, BigDecimal.ROUND_DOWN);
            BeanUtils.copyProperties(productInfo, orderDetail);
            orderDetail.setOrderId(orderId);
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetailDao.insert(orderDetail);
        }
        orderDTO.setOrderAmount(payAll);

        /** todo 扣库存（调用商品服务）*/
        List<CartDTO> cars = orderDTO.getList().stream()
                .map(orderDetail -> new CartDTO(orderDetail.getProductId(), orderDetail.getProductQuantity()))
                .collect(Collectors.toList());
        productClient.decreaseStock(cars);


        /** 订单入库(伪代码)*/
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderStatus(OrderStatus.NEW.getCode());
        orderMaster.setPayStatus(PayStatus.WAIT.getCode());
        orderMasterDao.insert(orderMaster);
        return orderDTO;
    }


}
